package com.kg.alarmclock.ui

import android.app.Activity
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.text.TextUtils
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.kg.alarmclock.Constant
import com.kg.alarmclock.R
import com.kg.alarmclock.base.BaseActivity
import com.kg.alarmclock.event.AlarmClockDeleteEvent
import com.kg.alarmclock.event.AlarmClockEvent
import com.kg.alarmclock.event.AlarmClockSwitchEvent
import com.kg.alarmclock.model.AlarmClockEntity
import com.kg.alarmclock.service.AlarmClockIntentService
import com.kg.alarmclock.service.AlarmClockReceiver
import com.kg.alarmclock.utils.DataUtils
import com.kg.alarmclock.utils.RxBus
import com.kg.alarmclock.utils.StringUtils
import com.kg.alarmclock.viewholder.AlarmClockHolder
import com.kg.alarmclock.viewholder.databean.AlarmClockBean
import com.steve.creact.library.adapter.CommonRecyclerAdapter
import com.steve.creact.library.display.DisplayBean
import kotlinx.android.synthetic.main.activity_main.*

/**
 * 首页
 */
class MainActivity : BaseActivity() {

    companion object {
        val REQUEST_ADD = 1
        val REQUEST_EDIT = 2
    }

    private var isEmpty = true
    private var entities = ArrayList<AlarmClockEntity>()
    private var position = 0

    private var pendingIntentRequestCode = 0

    private val adapter = CommonRecyclerAdapter()
    private val displayBeans = ArrayList<DisplayBean<AlarmClockHolder>>()
    private val manager = LinearLayoutManager(this)
    private var am: AlarmManager? = null

    override fun getLayout(): Int {
        return R.layout.activity_main
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_ADD) {
                var entity =
                    data!!.getSerializableExtra(AlarmClockSettingActivity.ENTITY_SAVE) as AlarmClockEntity

                if (entity.pendingIntentRequestCode == 0) {
                    pendingIntentRequestCode++
                    entity.pendingIntentRequestCode = pendingIntentRequestCode * 10
                }

                if (TextUtils.isEmpty(entity.action)) {
                    entity.action =
                        "${entity.hour}${entity.minute}${entity.pendingIntentRequestCode}"
                }
                addEntity(entity)
            } else if (requestCode == REQUEST_EDIT) {
                var entity =
                    data!!.getSerializableExtra(AlarmClockSettingActivity.ENTITY_SAVE) as AlarmClockEntity

                updateEntity(position, entity)
            }
        } else
            super.onActivityResult(requestCode, resultCode, data)
    }

    override fun onPause() {
        DataUtils.save(entities)
        super.onPause()
    }

    override fun initView() {
        addSubscribe(RxBus.INSTACE.asFlowable()
            .subscribe { o ->
                if (o is AlarmClockEvent) {
                    position = o.position
                    var intent = Intent(MainActivity@ this, AlarmClockSettingActivity::class.java)
                    intent.putExtra(
                        AlarmClockSettingActivity.TYPE,
                        AlarmClockSettingActivity.TYPE_EDIT
                    )
                    intent.putExtra(AlarmClockSettingActivity.ENTITY, o.entity)
                    startActivityForResult(intent, REQUEST_EDIT)
                } else if (o is AlarmClockSwitchEvent) {
                    var position = o.position
                    var entity = entities[position]
                    if (o.isCheck) {
                        entity.isChoose = true
                        setAlarm(entity)
                    } else {
                        entity.isChoose = false
                        cancelAlarm(entity)
                    }
                } else if (o is AlarmClockDeleteEvent) {
                    adapter.removeData(position)
                    cancelAlarm(o.entity)
                    entities.removeAt(position)
                }
            })

        list_alarm_clock.layoutManager = manager
        am = getSystemService(Context.ALARM_SERVICE) as AlarmManager

        DataUtils.init(this)
        initEntities()

        add_alarm_clock.setOnClickListener {
            var intent = Intent(MainActivity@ this, AlarmClockSettingActivity::class.java)
            intent.putExtra(AlarmClockSettingActivity.TYPE, AlarmClockSettingActivity.TYPE_ADD)
            startActivityForResult(intent, REQUEST_ADD)
        }
    }

    private fun setAlarm(entity: AlarmClockEntity) {
        var intent = Intent()
        intent.setAction("com.service.alarmclock")
        intent.setPackage("com.kg.alarmclock")
        intent.putExtra(AlarmClockIntentService.ENTITY, entity)
        intent.putExtra(AlarmClockIntentService.TYPE, AlarmClockIntentService.TYPE_SET)
        startService(intent)
    }

    private fun cancelAlarm(entity: AlarmClockEntity) {
        var intent = Intent()
        intent.setAction("com.service.alarmclock")
        intent.setPackage("com.kg.alarmclock")
        intent.putExtra(AlarmClockIntentService.ENTITY, entity)
        intent.putExtra(AlarmClockIntentService.TYPE, AlarmClockIntentService.TYPE_CANCEL)
        startService(intent)
    }

    private fun initEntities() {
        entities = DataUtils.getList() as ArrayList<AlarmClockEntity>

        for (entity in entities) {
            setAlarm(entity)
            displayBeans.add(AlarmClockBean(entity))
        }

        adapter.loadData(displayBeans)
        list_alarm_clock.adapter = adapter
    }

    private fun addEntity(entity: AlarmClockEntity) {
        isEmpty = adapter.itemCount == 0

        if (displayBeans.size > 0)
            displayBeans.clear()

        displayBeans.add(AlarmClockBean(entity))
        var position = insertEntities(entity)

        adapter.insertData(
            position,
            displayBeans as List<DisplayBean<AlarmClockHolder>>?
        )

        setAlarm(entity)
    }

    private fun updateEntity(position: Int, entity: AlarmClockEntity) {
        var displayBean = adapter.getItem(position) as AlarmClockBean
        displayBean.data = entity
        entities[position] = entity
        adapter.notifyDataSetChanged()

        setAlarm(entity)
    }

    private fun insertEntities(entity: AlarmClockEntity): Int {
        var position = 0

        entities.add(entity)
        var size = entities.size
        position = size - 1

        if (size > 1)
            for (index in size - 1 downTo 1) {
                var entityAfter = entities[index]
                var entityBefore = entities[index - 1]

                if (entityAfter.hour < entityBefore.hour
                    || (entityAfter.hour == entityBefore.hour
                            && entityAfter.minute < entityBefore.minute)
                ) {
                    var temp = entityBefore
                    entities[index - 1] = entityAfter
                    entities[index] = temp
                    position--
                }
            }
        return position
    }
}
